/**************************************************************************************************
 * *
 * HUSONG PROPRIETARY INFORMATION                                          *
 * *
 * The information contained herein is proprietary to HUSONG                           *
 * and shall not be reproduced or disclosed in whole or in part                       *
 * or used for any design or manufacture                                     *
 * without direct written authorization from HUSONG.                               *
 * *
 * Copyright (c) 2015 by HUSONG.  All rights reserved.                               *
 **************************************************************************************************/

package com.husong.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.husong.cons.MessageCons;
import com.husong.cons.OrderCons;
import com.husong.cons.OrderConstants;
import com.husong.cons.ProgressCons;
import com.husong.cons.QueryOrderType;
import com.husong.cons.ReturnCodeAndMsg;
import com.husong.entity.Address;
import com.husong.entity.Complain;
import com.husong.entity.Evaluate;
import com.husong.entity.Invite;
import com.husong.entity.Message;
import com.husong.entity.Order;
import com.husong.entity.OrderBroker;
import com.husong.entity.OrderIndexList;
import com.husong.entity.OrderInfo;
import com.husong.entity.OrderList;
import com.husong.entity.OrderPic;
import com.husong.entity.OrderProgress;
import com.husong.entity.OrderWaitList;
import com.husong.entity.Red;
import com.husong.entity.User;
import com.husong.entity.Zan;
import com.husong.impl.base.BaseService;
import com.husong.pojo.ActivityFundPoolBean;
import com.husong.pojo.ActivityFundPoolLogBean;
import com.husong.pojo.AdvertBean;
import com.husong.pojo.AdvertModel;
import com.husong.pojo.ConmentBean;
import com.husong.pojo.EvaluateBean;
import com.husong.pojo.OrderBean;
import com.husong.pojo.OrderBrokerBean;
import com.husong.pojo.OrderTypeBean;
import com.husong.pojo.RedBean;
import com.husong.pojo.ReturnJsonBean;
import com.husong.pojo.TipBean;
import com.husong.pojo.UserWalletBean;
import com.husong.pojo.UserWalletLogBean;
import com.husong.pojo.ZanBean;
import com.husong.service.OrderDataService;
import com.husong.util.BeanUtil;
import com.husong.util.PointUtil;
import com.husong.util.UUIDUtil;

/**
 * create by MaxMin.
 * <p/>
 * email: tjljob@126.com
 * <p/>
 * date:  2015年11月12日 17:38.
 */
public class OrderServiceImpl extends BaseService implements OrderDataService {

    /**
     * 获取订单详情
     *
     * @param orderid
     *
     * @return
     */
    @Override
    public Order get(String orderid) {
    	OrderBean bean=orderMapper.get(orderid);
    	Order order=BeanUtil.build(bean);
        return order;
    }
    
    /**
     * 获取订单详情
     *
     * @param orderid
     *
     * @return
     */
    @Override
    public OrderInfo getOrderInfo(String orderid) {
    	OrderBean bean=orderMapper.get(orderid);
    	OrderInfo order=BeanUtil.buildOrderInfo(bean);
    	return order;
    }

    /**
     * 发布订单
     *
     * @param order
     *
     * @return
     */
    @Override
    public int create(Order order) {
        return orderMapper.create(order);
    }
    
    /**
     * 发布订单
     *
     * @param order
     *
     * @return
     */
    @Override
    public void create(Order order,String[] picpaths) {
    	Timestamp currTime=new Timestamp(System.currentTimeMillis());
    	orderMapper.create(order);
    	if(picpaths!=null&&picpaths.length>0){
    		for(String picpath:picpaths){
    			OrderPic pic =new OrderPic();
    			pic.setPath(picpath);
    			pic.setOrderId(order.getOrderId());
    			pic.setCreateDate(currTime);
    			pic.setPicId(UUIDUtil.getUUID());
    			orderMapper.saveOrderPic(pic);
    		}
    	}
    }

    /**
     * 按类型查询所有
     *
     * @param type
     *
     * @return
     */
    @Override
    public List<Order> findAll(int type, String cityname,String lastDate,Long lastorderid) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("type", type);
        params.put("cityname", cityname);
        params.put("lastDate", lastDate);
        params.put("lastorderid", lastorderid);
        List<OrderBean> beans=orderMapper.findAll(params);
        List<Order> orders=new ArrayList<Order>();
        for(OrderBean bean:beans){
        	Order order=BeanUtil.build(bean);
        	orders.add(order);
        }
        return orders;
    }

    @Override
    public List<OrderList> findOrdersByUserIdAndType(String key, int type,String lastDate,Long lastorderid) {
    	Map<String,Object> params=new HashMap<String, Object>();
    	params.put("key", key);
    	params.put("lastDate", lastDate);
    	params.put("lastorderid", lastorderid);
    	List<OrderList> orders=new ArrayList<OrderList>();
        if (type == QueryOrderType.QUERY_ORDER_TYPE_TASKING) {
        	List<OrderBean> beans=orderMapper.findTaskingOrdersByUserId(params);
            for(OrderBean bean:beans){
            	OrderList order=BeanUtil.buildOrderList(bean);
            	orders.add(order);
            }
            return orders;
        } else if (type == QueryOrderType.QUERY_ORDER_TYPE_HISTORY) {
        	List<OrderBean> beans=orderMapper.findHistoryOrdersByUserId(params);
            for(OrderBean bean:beans){
            	OrderList order=BeanUtil.buildOrderList(bean);
            	orders.add(order);
            }
            return orders;
        } else {
            return null;
        }
    }

    @Override
    public List<OrderList> findOrdersByBrokerAndType(String key, int type,String lastDate,Long lastorderid) {
    	Map<String,Object> params=new HashMap<String, Object>();
    	params.put("key", key);
    	params.put("lastDate", lastDate);
    	params.put("lastorderid", lastorderid);
    	List<OrderList> orders=new ArrayList<OrderList>();
    	
        if (type == QueryOrderType.QUERY_ORDER_TYPE_TASKING) {
        	 List<OrderBean> beans=orderMapper.findTaskingOrdesrByBroker(params);
             for(OrderBean bean:beans){
            	 OrderList order=BeanUtil.buildOrderList(bean);
             	orders.add(order);
             }
            return orders;
        } else if (type == QueryOrderType.QUERY_ORDER_TYPE_HISTORY) {
        	List<OrderBean> beans=orderMapper.findHistorygOrdesrByBroker(params);
            for(OrderBean bean:beans){
            	OrderList order=BeanUtil.buildOrderList(bean);
            	orders.add(order);
            }
            return orders;
        } else {
            return null;
        }
    }

    /**
     * 获取待抢单列表
     *
     * @param cityname 城市名
     * @param type 订单类型
     *
     * @return
     */
    @Override
    public List<OrderWaitList> findWaitOrders(String key,String cityname, Integer type,String lastDate,Long lastorderid) {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("key",key);
        params.put("cityname",cityname);
        params.put("type",type);
        params.put("lastDate",lastDate);
        params.put("lastorderid", lastorderid);
        List<OrderBean> beans=orderMapper.findWaitOrders(params);
        List<OrderWaitList> orders=new ArrayList<OrderWaitList>();
        for(OrderBean bean:beans){
        	OrderWaitList order=BeanUtil.buildOrderWaitList(bean);
        	orders.add(order);
        }
        return orders;
    }
    /**
     * 获取首页呼单列表
     *
     * @param cityname 城市名
     * @param type 订单类型
     *
     * @return
     */
    @Override
    public List<OrderIndexList> findIndexOrders(String cityname, Integer type,String lastDate,Long lastorderid) {
    	Map<String,Object> params = new HashMap<String,Object>();
    	params.put("cityname",cityname);
    	params.put("type",type);
    	params.put("lastDate",lastDate);
    	params.put("lastorderid", lastorderid);
    	List<OrderBean> beans=orderMapper.findIndexOrders(params);
    	List<OrderIndexList> orders=new ArrayList<OrderIndexList>();
    	if(beans==null){
    		return orders;
    	}
    	for(OrderBean bean:beans){
    		if(bean==null){
    			continue;
    		}
    		OrderIndexList order=BeanUtil.buildOrderIndexList(bean);
    		orders.add(order);
    	}
    	return orders;
    }

    /**
     * 取消订单
     *
     * @param orderId
     *
     * @return
     */
    @Override
    public int delete(String orderId) {
        return orderMapper.delete(orderId);
    }
    /**
     * 申请取消订单
     *
     * @param orderId
     *
     * @return
     */
    @Override
    public int need_cancel(String orderId) {
    	int result=orderMapper.need_cancel(orderId);
    	return result;
    }

	@Override
	public Timestamp getLastGrabOrderTimeByBrokerId(String brokerid) {
		List<Timestamp> times=orderMapper.getGrabOrderTimeByBrokerId(brokerid);
		if(times==null||times.size()<1){
			return null;
		}
		return times.get(0);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public int grabOrder(String orderid, String userId, String lng, String lat) {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("orderid", orderid);
		params.put("status", 2);
		params.put("oriStatus", 1);
		int count=orderMapper.updateOrderStatus(params);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id", UUIDUtil.getUUID());
		map.put("userId", userId);
		map.put("orderId", orderid);
		map.put("isChecked", 0);
		map.put("lng", lng);
		map.put("lat", lat);
		map.put("createDate", new Timestamp(System.currentTimeMillis()));
		count=orderMapper.insertOrderBroker(map);
		return count;
	}

	@Override
	public List<OrderBroker> chooseBrokerList(String orderid, Integer type) {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("orderid", orderid);
		params.put("type", type);
		List<OrderBroker> list=orderMapper.chooseBrokerList(params);
		for(OrderBroker broker:list){
			broker.setTitle(PointUtil.convertToTitle(broker.getPoint()));
		}
		return list;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public int chooseBroker(String orderbrokerid) {
		OrderBrokerBean bean=orderMapper.getOrderBrokerBean(orderbrokerid);
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("orderid", bean.getOrder_id());
		params.put("broker_id", bean.getUser_id());
		params.put("status", 3);
		params.put("oriStatus", 2);
		int count=orderMapper.updateOrder(params);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id", orderbrokerid);
		map.put("is_checked", 1);
		count=orderMapper.updateOrderBroker(map);
		
		final OrderBrokerBean ob=bean;
		Order order=get(bean.getOrder_id());
		final Order forder= order;
		final OrderBrokerBean b=bean;
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				List<User> users=orderMapper.getUsers(forder.getOrderId());
				//极光推送
				String msg = "";
				for (User user : users) {
					if (user.getUserId().equals(b.getUser_id())) {
						msg = OrderCons.CHOOSE_BROKER;
					}else {
						msg = OrderCons.CHOOSE_ANATHER_BROKER;
					}
				jPush.pushWithAlias(jPush.getUserClient(), msg, user.getNotifyid());
				}
				
				Message message = new Message(OrderCons.CHOOSE_BROKER, forder.getBrokerId(),
						MessageCons.USER_TYPE_BROKER,
						MessageCons.MESSAGE_TYPE_ORDER);
				message.setCreatetime(new Timestamp(System.currentTimeMillis()));
				orderMapper.addMessage(message);
				//呼单状态记录
				OrderProgress progress=new OrderProgress();
				progress.setId(UUIDUtil.getUUID());
				progress.setUser_msg(ProgressCons.ORDER_ACCEPTED_MSG);
				progress.setContent(ProgressCons.ORDER_ACCEPTED_CONTENT);
				progress.setOrderid(ob.getOrder_id());
				progress.setOrder_status(OrderConstants.ORDER_HAD_CHECKED);
				progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
				orderMapper.addOrderProgress(progress);
			}
		}).start();
		return count;
	}

	@Override
	public int buy(String orderid, BigDecimal fee) {
		OrderBean bean=orderMapper.get(orderid);
		Integer adverttype=bean.getAdvert_type();
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("status", 4);
		params.put("oriStatus", 3);
		params.put("adverttype", adverttype);
		params.put("advertId", bean.getAdvert_id());
		params.put("fee", fee);
		params.put("orderid", orderid);
		int count=orderMapper.updateOrderFee(params);	
		return count;
	}

	@Override
	public int confirm(String orderid) {
		OrderBean bean=orderMapper.get(orderid);
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("orderid", orderid);
		params.put("status", 7);
		if(bean.getOrder_type_id()==1){//代办
			params.put("oriStatus", 6);
		}else if(bean.getOrder_type_id()==2){//代购
			params.put("oriStatus", 4);
		}else if(bean.getOrder_type_id()==3){//代送
			params.put("oriStatus", 5);
		}else{
			return 0;
		}
		int count=orderMapper.updateOrderStatus(params);
		return count;
	}

	@Override
	public int got(String orderid) {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("orderid", orderid);
		params.put("status", 5);
		params.put("oriStatus", 3);
		int count=orderMapper.updateOrderStatus(params);
		return count;
	}

	@Override
	public int dealed(String orderid) {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("orderid", orderid);
		params.put("status", 6);
		params.put("oriStatus", 3);
		int count=orderMapper.updateOrderStatus(params);
		
		final String orderId=orderid;
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				//极光推送
				Order order=get(orderId);
				User user=userMapper.getUserById(order.getUserId());
				//呼单状态记录
				OrderBean bean=orderMapper.get(orderId);
				if(bean.getOrder_type_id()==1){//代办
					jPush.pushWithAlias(jPush.getUserClient(),OrderCons.FINISHED_STR, user.getNotifyid());
					
					Message message = new Message(OrderCons.FINISHED_STR,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					addMessage(message);
					
					OrderProgress progress=new OrderProgress();
					progress.setId(UUIDUtil.getUUID());
					progress.setUser_msg(ProgressCons.ORDER_FINISHED_MSG);
					progress.setContent(ProgressCons.ORDER_FINISHED_CONTENT);
					progress.setOrderid(orderId);
					progress.setOrder_status(OrderConstants.ORDER_HAD_CHECKED);
					progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderMapper.addOrderProgress(progress);
				}else if(bean.getOrder_type_id()==3){//代送
					jPush.pushWithAlias(jPush.getUserClient(),OrderCons.FINISHED_SONGDA_STR, user.getNotifyid());
					
					Message message = new Message(OrderCons.FINISHED_SONGDA_STR,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					addMessage(message);
					
					OrderProgress progress=new OrderProgress();
					progress.setId(UUIDUtil.getUUID());
					progress.setUser_msg(ProgressCons.ORDER_SENDED_MSG);
					progress.setContent(ProgressCons.ORDER_SENDED_CONTENT);
					progress.setOrderid(orderId);
					progress.setOrder_status(OrderConstants.ORDER_HAD_CHECKED);
					progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderMapper.addOrderProgress(progress);
				}
				
			}
		}).start();
		
		return count;
	}

	@Override
	public int addOrderProgress(OrderProgress progress) {
		return orderMapper.addOrderProgress(progress);
	}

	@Override
	public List<OrderProgress> getOrderProgressesByOrderId(String orderid) {
		return orderMapper.getOrderProgressesByOrderId(orderid);
	}

	@Override
	public List<TipBean> getTips() {
		return orderMapper.getTips();
	}

	@Override
	public TipBean getTipById(long id) {
		return orderMapper.getTipById(id);
	}

	@Override
	public List<OrderTypeBean> getOrderTypes() {
		return orderMapper.getOrderTypes();
	}

	@Override
	public List<Address> getAddresses(String user_id) {
		return orderMapper.getAddressesByUserId(user_id);
	}

	@Override
	public int addAddress(Address address) {
		return orderMapper.insertAddress(address);
	}
	
	@Override
	public int updateAddress(Address address) {
		return orderMapper.updateAddress(address);
	}

	@Override
	public int deletAddress(String id) {
		return orderMapper.deleteAddress(id);
	}

	@Override
	public List<AdvertModel> getAdverts(String cityname) {
		List<AdvertModel> adverts=new ArrayList<AdvertModel>();
		List<AdvertBean> beans=orderMapper.getAdverts(cityname);
		for(AdvertBean bean:beans){
			AdvertModel advert=BeanUtil.buildAdvertModel(bean);
			adverts.add(advert);
		}
		return adverts;
	}

	@Override
	public Integer getBrokerCounts(String cityname) {
		return orderMapper.getBrokerCounts(cityname);
	}

	@Override
	public Red getRed(String redid) {
		return orderMapper.getRed(redid);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public ReturnJsonBean walletPay(String user_id,String orderid, String redid) {
		ReturnJsonBean rb = new ReturnJsonBean();
		UserWalletBean wallet=userMapper.getUsefullUserWalletBeanByUserId(user_id);
		Order order=get(orderid);
		BigDecimal fee=order.getFee();
		BigDecimal tip=order.getTip();
		BigDecimal discount=order.getDiscount();
		
		BigDecimal totalFee=fee.add(tip).subtract(discount);
		BigDecimal giveMoney =new BigDecimal(0);
		Red red=null;
		if(redid!=null&&!"".equals(redid.trim())){
			red=getRed(redid);
			giveMoney=red.getAmount();
		}
		totalFee=totalFee.subtract(giveMoney);
		
		if(totalFee.doubleValue()<=0){
			totalFee=BigDecimal.valueOf(0.01);
		}
		
		BigDecimal balance=wallet.getRecharge_amount();
		
		if(balance.doubleValue()<totalFee.doubleValue()){
			returnFail(rb, ReturnCodeAndMsg.WALLET_BALANCE_IS_LACK, ReturnCodeAndMsg.WALLET_BALANCE_IS_LACK_MSG);
			return rb;
		}
		
		//1.扣除用户余额
		Map<String,Object> userParams=new HashMap<String, Object>();
		userParams.put("user_id", user_id);
		userParams.put("recharge_amount", totalFee.multiply(BigDecimal.valueOf(-1)));
		userMapper.updateBalance(userParams);
		//2.增加用户钱包记录
		UserWalletLogBean userWalletLog=new UserWalletLogBean();
		userWalletLog.setAmount(totalFee.multiply(BigDecimal.valueOf(-1)));
		userWalletLog.setId(UUIDUtil.getUUID());
		userWalletLog.setOrder_id(orderid);
		userWalletLog.setTrade_type(3);
		if(order.getOrderTypeId()==1){
			
			userWalletLog.setTrade_desc("代办");
		}else if(order.getOrderTypeId()==2){
			
			userWalletLog.setTrade_desc("代购");
		}else if(order.getOrderTypeId()==3){
			
			userWalletLog.setTrade_desc("代送");
		}
		userWalletLog.setTrade_time(new Timestamp(System.currentTimeMillis()));
		userWalletLog.setUser_id(user_id);
		userWalletLog.setOrder_no(order.getOrderNo());
		userMapper.addWalletLog(userWalletLog);
		//3.给经纪人钱包加钱
		Map<String,Object> brokerParams=new HashMap<String, Object>();
		UserWalletBean brokerWallet=userMapper.getUsefullUserWalletBeanByUserId(order.getBrokerId());//判断经纪人钱包是否存在
		if(brokerWallet==null){
			brokerWallet=new UserWalletBean();
			brokerWallet.setCreate_time(new Timestamp(System.currentTimeMillis()));
			brokerWallet.setFrozen_amount(BigDecimal.ZERO);
			brokerWallet.setPay_password(null);
			brokerWallet.setPurchase_amount(BigDecimal.ZERO);
			brokerWallet.setRecharge_amount(BigDecimal.ZERO);
			brokerWallet.setStatus(1);
			brokerWallet.setTip_amount(BigDecimal.ZERO);
			brokerWallet.setUser_id(order.getBrokerId());
			userMapper.addUserWallet(brokerWallet);
		}
		brokerParams.put("user_id", order.getBrokerId());
		brokerParams.put("purchase_amount", fee);
		brokerParams.put("tip_amount", tip);
		userMapper.updateBrokerBalance(brokerParams);
		//4.增加经纪人钱包记录
		UserWalletLogBean brokerWalletLog=new UserWalletLogBean();
		brokerWalletLog.setPurchase_amount(fee);
		brokerWalletLog.setTip_amount(tip);
		brokerWalletLog.setId(UUIDUtil.getUUID());
		brokerWalletLog.setOrder_id(orderid);
		if(order.getOrderTypeId()==1){
			
			brokerWalletLog.setTrade_desc("代办");
		}else if(order.getOrderTypeId()==2){
			
			brokerWalletLog.setTrade_desc("代购");
		}else if(order.getOrderTypeId()==3){
			
			brokerWalletLog.setTrade_desc("代送");
		}
		brokerWalletLog.setTrade_type(2);
		brokerWalletLog.setTrade_time(new Timestamp(System.currentTimeMillis()));
		brokerWalletLog.setUser_id(order.getBrokerId());
		brokerWalletLog.setOrder_no(order.getOrderNo());
		userMapper.addWalletLog(brokerWalletLog);
		//5.修改订单状态
		Map<String,Object> orderParams=new HashMap<String,Object>();
		orderParams.put("status", 8);
		orderParams.put("orderid", orderid);
		orderParams.put("oriStatus", order.getStatusId());
		orderMapper.updateOrderStatus(orderParams);
		//6.红包状态修改
		if(redid!=null&&!"".equals(redid.trim())){
			Map<String,Object> redParams=new HashMap<String,Object>();
			redParams.put("red_status", 2);
			redParams.put("order_id", orderid);
			redParams.put("id", redid);
			orderMapper.updateRed(redParams);
			//7.资金池修改
			if(totalFee.doubleValue()<giveMoney.doubleValue()){
				giveMoney=totalFee;
			}
			
			Map<String,Object> redparams=new HashMap<String,Object>();
			redparams.put("activity_type", 2);
			redparams.put("city_name", order.getCityname());
			ActivityFundPoolBean redpool=orderMapper.getActivityFundPool(redparams);
			
			Map<String,Object> redupdate=new HashMap<String,Object>();
			redupdate.put("id", redpool.getId());
			redupdate.put("amount", giveMoney);
			orderMapper.updateActivityFundPool(redupdate);
			//8.资金池记录
			ActivityFundPoolLogBean redlog=new ActivityFundPoolLogBean();
			redlog.setId(UUIDUtil.getUUID());
			redlog.setActivity_desc("新手红包优惠");
			redlog.setActivity_type(2);
			redlog.setAmount(giveMoney);
			redlog.setCity_name(order.getCityname());
			redlog.setCreate_time(new Timestamp(System.currentTimeMillis()));
			redlog.setFund_code(redpool.getFund_code());
			redlog.setFund_id(redpool.getId());
			redlog.setOrder_id(order.getOrderId());
			redlog.setUser_id(user_id);
			orderMapper.addActivityFundPoolLog(redlog);
		}
		
		if(discount!=null&&discount.doubleValue()>0){
			//7.资金池修改
			Map<String,Object> discountparams=new HashMap<String,Object>();
			discountparams.put("activity_type", 1);
			discountparams.put("city_name", order.getCityname());
			ActivityFundPoolBean discountpool=orderMapper.getActivityFundPool(discountparams);
			
			Map<String,Object> discountupdate=new HashMap<String,Object>();
			discountupdate.put("id", discountpool.getId());
			discountupdate.put("amount", discount);
			orderMapper.updateActivityFundPool(discountupdate);
			//8.资金池记录
			ActivityFundPoolLogBean discountlog=new ActivityFundPoolLogBean();
			discountlog.setId(UUIDUtil.getUUID());
			discountlog.setActivity_desc("商品折扣");
			discountlog.setActivity_type(1);
			discountlog.setAmount(discount);
			discountlog.setCity_name(order.getCityname());
			discountlog.setCreate_time(new Timestamp(System.currentTimeMillis()));
			discountlog.setFund_code(discountpool.getFund_code());
			discountlog.setFund_id(discountpool.getId());
			discountlog.setOrder_id(order.getOrderId());
			discountlog.setUser_id(user_id);
			orderMapper.addActivityFundPoolLog(discountlog);
		}
		
		final String orderId=orderid;
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				//极光推送
				
				Order order=get(orderId);
				User user=userMapper.getUserById(order.getBrokerId());
				jPush.pushWithAlias(jPush.getUserClient(), OrderCons.PAY_SUCCESS, user.getNotifyid());
				
				Message message = new Message(OrderCons.PAY_SUCCESS, order.getBrokerId(),
						MessageCons.USER_TYPE_BROKER,
						MessageCons.MESSAGE_TYPE_ORDER);
				message.setCreatetime(new Timestamp(System.currentTimeMillis()));
				addMessage(message);
				Map<String, Object> params=new HashMap<String, Object>();
				params.put("point", 5);
				params.put("user_id", order.getUserId());
				userMapper.updatePoint(params);
				//呼单状态记录
					OrderProgress progress=new OrderProgress();
					progress.setId(UUIDUtil.getUUID());
					progress.setUser_msg(ProgressCons.ORDER_PAYED_MSG);
					progress.setContent(ProgressCons.ORDER_PAYED_CONTENT);
					progress.setOrderid(orderId);
					progress.setOrder_status(OrderConstants.ORDER_NEED_EVALUATE);
					progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderMapper.addOrderProgress(progress);
				
			}
		}).start();
		
		returnSuccess(rb);
		return rb;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public int addEvaluate(String orderid,String userid,String content,BigDecimal point) {
		EvaluateBean evaluate=new EvaluateBean();
		evaluate.setContent(content);
		evaluate.setCreate_date(new Timestamp(System.currentTimeMillis()));
		evaluate.setId(UUIDUtil.getUUID());
		evaluate.setOrderid(orderid);
		evaluate.setPoint(point);
		evaluate.setUserid(userid);
		Map<String,Object> orderParams=new HashMap<String,Object>();
		orderParams.put("status", 9);
		orderParams.put("orderid", orderid);
		orderParams.put("oriStatus", 8);
		final int count=orderMapper.updateOrderStatus(orderParams);
		final String orderId=orderid;
		final String user_id=userid;
		final double p=point.doubleValue();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				//极光推送
				Order order=get(orderId);
				Map<String, Object> params=new HashMap<String, Object>();
				params.put("point", 5);
				params.put("user_id", user_id);
				userMapper.updatePoint(params);
				
				if(p>=4){
					Map<String, Object> params1=new HashMap<String, Object>();
					params1.put("point", 5);
					if(order.getBrokerId().equals(user_id)){
						params1.put("user_id", order.getUserId());
					}else{
						params1.put("user_id", order.getBrokerId());
					}
					userMapper.updatePoint(params1);
				}else if(p<3){
					Map<String, Object> params1=new HashMap<String, Object>();
					params1.put("point", -10);
					if(order.getBrokerId().equals(user_id)){
						params1.put("user_id", order.getUserId());
					}else{
						params1.put("user_id", order.getBrokerId());
					}
					userMapper.updatePoint(params1);
				}
				
				
				//呼单状态记录
				if(count>0){
					
					
					OrderProgress progress1=new OrderProgress();
					progress1.setId(UUIDUtil.getUUID());
					progress1.setUser_msg(ProgressCons.ORDER_EVALUATED_MSG);
					progress1.setContent(ProgressCons.ORDER_EVALUATED_CONTENT);
					progress1.setOrderid(orderId);
					progress1.setOrder_status(OrderConstants.ORDER_FINISH);
					progress1.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderMapper.addOrderProgress(progress1);
					
					OrderProgress progress=new OrderProgress();
					progress.setId(UUIDUtil.getUUID());
					progress.setUser_msg("");
					progress.setContent(ProgressCons.ORDER_FINISHED);
					progress.setOrderid(orderId);
					progress.setOrder_status(OrderConstants.ORDER_FINISH);
					progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
					orderMapper.addOrderProgress(progress);
					
					Integer finishCount=orderMapper.getFinishedOrderCount(user_id);
					if(finishCount==null||finishCount<1){
						Invite invite=userMapper.getNotPrizeInvite(user_id);
						User user=userMapper.getUserById(invite.getInvite_user_id());
						if(invite!=null){
							Calendar today=Calendar.getInstance();
							today.add(Calendar.DAY_OF_MONTH, 30);
							Red red=new Red();
							red.setActive_begin_time(new Timestamp(System.currentTimeMillis()));
							red.setActive_end_time(new Timestamp(today.getTime().getTime()));
							red.setAmount(BigDecimal.valueOf(5));
							red.setCityname(user.getCityName());
							red.setCreate_date(new Timestamp(System.currentTimeMillis()));
							red.setId(UUIDUtil.getUUID());
							red.setRed_desc("推荐奖励红包5元");
							red.setRed_status(1);
							red.setRed_type(2);
							red.setUser_id(invite.getInvite_user_id());
							orderMapper.addRed(red);
							Red red2=new Red();
							red2.setActive_begin_time(new Timestamp(System.currentTimeMillis()));
							red2.setActive_end_time(new Timestamp(today.getTime().getTime()));
							red2.setAmount(BigDecimal.valueOf(5));
							red2.setCityname(user.getCityName());
							red2.setCreate_date(new Timestamp(System.currentTimeMillis()));
							red2.setId(UUIDUtil.getUUID());
							red2.setRed_desc("推荐奖励红包5元");
							red2.setRed_status(1);
							red2.setRed_type(2);
							red2.setUser_id(user_id);
							orderMapper.addRed(red2);
						}
					}
				}
				
			}
		}).start();
		return orderMapper.addEvaluate(evaluate);
	}

	@Override
	public List<Evaluate> getBrokerToMeEvalustes(String user_id,String lastDateStr,Long lastrowid) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		List<Evaluate> evaluates=new ArrayList<Evaluate>();
		List<EvaluateBean> beans=orderMapper.getBrokerToMeEvalustes(params);
		for(EvaluateBean bean:beans){
			Evaluate evaluate=BeanUtil.buildEvaluate(bean);
			evaluates.add(evaluate);
		}
		return evaluates;
	}

	@Override
	public List<Evaluate> getUserToMeEvalustes(String user_id,String lastDateStr,Long lastrowid) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		List<Evaluate> evaluates=new ArrayList<Evaluate>();
		List<EvaluateBean> beans=orderMapper.getUserToMeEvalustes(params);
		for(EvaluateBean bean:beans){
			Evaluate evaluate=BeanUtil.buildEvaluate(bean);
			evaluates.add(evaluate);
		}
		return evaluates;
	}

	@Override
	public List<Evaluate> getMeToBrokerEvalustes(String user_id,String lastDateStr,Long lastrowid) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		List<Evaluate> evaluates=new ArrayList<Evaluate>();
		List<EvaluateBean> beans=orderMapper.getMeToBrokerEvalustes(params);
		for(EvaluateBean bean:beans){
			Evaluate evaluate=BeanUtil.buildEvaluate(bean);
			evaluates.add(evaluate);
		}
		return evaluates;
	}

	@Override
	public List<Evaluate> getMeToUserEvalustes(String user_id,String lastDateStr,Long lastrowid) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		List<Evaluate> evaluates=new ArrayList<Evaluate>();
		List<EvaluateBean> beans=orderMapper.getMeToUserEvalustes(params);
		for(EvaluateBean bean:beans){
			Evaluate evaluate=BeanUtil.buildEvaluate(bean);
			evaluates.add(evaluate);
		}
		return evaluates;
	}

	@Override
	public List<ConmentBean> getComments(String orderid,String lastDateStr,Long lastrowid) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("orderid", orderid);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		List<ConmentBean> beans=orderMapper.getComments(params);
		return beans;
	}

	@Override
	public int addConment(String user_id, String order_id, String parent_commetn_id, String content) {
		ConmentBean conment=new ConmentBean();
		conment.setContent(content);
		conment.setCreate_date(new Timestamp(System.currentTimeMillis()));
		conment.setUpdate_date(new Timestamp(System.currentTimeMillis()));
		conment.setId(UUIDUtil.getUUID());
		conment.setOrder_id(order_id);
		conment.setParent_comment_id(parent_commetn_id);
		conment.setUser_id(user_id);
		User user=userMapper.getUserById(user_id);
		Order order =get(order_id);
		if(parent_commetn_id!=null&&!"".equals(parent_commetn_id)){
//			String message = user.getUsername()+"对你发布的订单进行了评价";
//			Message msg = new Message(message,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_COMMENT);
//			msg.setOrderId(order_id);
//			msg.setFromUserId(user_id);
//			msg.setCreatetime(new Timestamp(System.currentTimeMillis()));
//			orderMapper.addMessage(msg);
		}
			String message = user.getUsername()+"对你发布的订单进行了评价";
			Message msg = new Message(message,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_COMMENT);
			msg.setOrderId(order_id);
			msg.setFromUserId(user_id);
			msg.setCreatetime(new Timestamp(System.currentTimeMillis()));
			orderMapper.addMessage(msg);
		return orderMapper.addConment(conment);
	}

	@Override
	public int addZan(String user_id, String order_id) {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("user_id", user_id);
		params.put("order_id", order_id);
		ZanBean zan=orderMapper.getZan(params);
		
		Order order =get(order_id);
		User user=userMapper.getUserById(user_id);
		if(zan==null){
			zan=new ZanBean();
			zan.setCreate_date(new Timestamp(System.currentTimeMillis()));
			zan.setOrder_id(order_id);
			zan.setStatus(1);
			zan.setUser_id(user_id);
			orderMapper.addZan(zan);
			String message = user.getUsername()+"对你发布的订单点赞";
			Message msg = new Message(message,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ZAN);
			msg.setCreatetime(new Timestamp(System.currentTimeMillis()));
			msg.setOrderId(order_id);
			msg.setFromUserId(user_id);
			orderMapper.addMessage(msg);
			return  1;
		}
		
		if(zan.getStatus()==0){
			params.put("status", 1);
			orderMapper.updateZanStatus(params);
			return 1;
		}
		
		if(zan.getStatus()==1){
			params.put("status", 0);
			orderMapper.updateZanStatus(params);
			String message = user.getUsername()+"取消对你的点赞";
			Message msg = new Message(message,order.getUserId(),MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ZAN);
			msg.setCreatetime(new Timestamp(System.currentTimeMillis()));
			msg.setOrderId(order_id);
			msg.setFromUserId(user_id);
			orderMapper.addMessage(msg);
			return 0;
		}
		return 0;
	}

	@Override
	public Integer getZanCount(String order_id) {
		return orderMapper.getZanCount(order_id);
	}

	@Override
	public Integer getConmentCount(String order_id) {
		return orderMapper.getConmentCount(order_id);
	}

	@Override
	public List<Zan> getZans(String order_id) {
		return orderMapper.getZans(order_id);
	}

	@Override
	public Integer getEvaluateCount(Map<String, Object> params) {
		return orderMapper.getEvaluateCount(params);
	}

	@Override
	public List<RedBean> getReds(String userid) {
		List<Red> reds=orderMapper.getReds(userid);
		List<RedBean> beans=new ArrayList<RedBean>();
		for(Red red:reds){
			RedBean bean=BeanUtil.buildRed(red);
			beans.add(bean);
		}
		return beans;
	}
	@Override
	public List<RedBean> getUsefullReds(String userid) {
		List<Red> reds=orderMapper.getUsefullReds(userid);
		List<RedBean> beans=new ArrayList<RedBean>();
		for(Red red:reds){
			RedBean bean=BeanUtil.buildRed(red);
			beans.add(bean);
		}
		return beans;
	}

	@Override
	public int appendTip(int tipid, String orderid) {
		TipBean tip=orderMapper.getTipById(tipid);
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("tip", tip.getTip());
		params.put("orderid", orderid);
		return orderMapper.appendTip(params);
	}

	@Override
	public int addMessage(Message message) {
		return orderMapper.addMessage(message);
	}

	@Override
	public List<Message> getMessages(String userid, int type, String lastDateStr, Long lastrowid) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("userid", userid);
		params.put("type", type);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		return orderMapper.getMessages(params);
	}

	@Override
	public Integer complain(Complain complain) {
		return orderMapper.complain(complain);
	}

	@Override
	public Integer getProgeressCount(String orderid, int order_status) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("orderid", orderid);
		params.put("order_status", order_status);
		return orderMapper.getProgeressCount(params);
	}

	@Override
	public Integer getOrderBrokerCount(String order_id, String user_id) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("order_id", order_id);
		params.put("user_id", user_id);
		return orderMapper.getOrderBrokerCount(params);
	}
}
